//
//  UIBarButtonItem+Extention.m
//  CZXApp
//
//  Created by muxue on 2018/10/11.
//

#import "UIBarButtonItem+Extention.h"
#import <objc/message.h>

static const void *XBBarButtonItemAction = "BarButtonItemAction";
@implementation UIBarButtonItem (Extention)

+ (instancetype)itemWithImage:(UIImage *)image
                       action:(XBBarButtonAction)action {
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] init];
    barButtonItem.target = barButtonItem;
    barButtonItem.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    barButtonItem.style = UIBarButtonItemStylePlain;
    barButtonItem.action = @selector(clicked);
    barButtonItem.myAction = action;
    return barButtonItem;
}
+ (instancetype)itemWithTitle:(NSString *)title
                       action:(XBBarButtonAction)action {
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] init];
    barButtonItem.target = barButtonItem;
    barButtonItem.title = title;
    barButtonItem.style = UIBarButtonItemStylePlain;
    barButtonItem.action = @selector(clicked);
    barButtonItem.myAction = action;
    return barButtonItem;
}
+ (instancetype)buttonWithImage:(UIImage *)image action:(XBBarButtonAction)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 44, 44);
    [btn setImage:image
         forState:UIControlStateNormal];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    barButtonItem.target = barButtonItem;
    barButtonItem.style = UIBarButtonItemStylePlain;
    barButtonItem.action = @selector(clicked);
    barButtonItem.myAction = action;
    return barButtonItem;
}
+ (instancetype)buttonWithTitle:(NSString *)title
                         action:(XBBarButtonAction)action {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 44, 44);
    [btn setTitle:title
         forState:UIControlStateNormal];
    [btn setTitleColor:UIColor.blackColor
              forState:UIControlStateNormal];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    barButtonItem.target = barButtonItem;
    barButtonItem.style = UIBarButtonItemStylePlain;
    barButtonItem.action = @selector(clicked);
    barButtonItem.myAction = action;
    return barButtonItem;
}
- (void)clicked {
    if (self.myAction) {
        self.myAction();
    }
}
- (void)setMyAction:(XBBarButtonAction)action {
    objc_setAssociatedObject(self, XBBarButtonItemAction, action, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (XBBarButtonAction)myAction {
    return objc_getAssociatedObject(self, XBBarButtonItemAction);
}
@end
